package com.dify.knowledge.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dify.knowledge.entity.QuestionRecord;
import com.dify.knowledge.service.QuestionAnswerService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 问答控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/qa")
@Validated
public class QuestionAnswerController {

    private final QuestionAnswerService questionAnswerService;

    public QuestionAnswerController(QuestionAnswerService questionAnswerService) {
        this.questionAnswerService = questionAnswerService;
    }

    /**
     * 提交问题
     * 
     * @param request 问题请求
     * @return 问答结果
     */
    @PostMapping("/ask")
    public ResponseEntity<QuestionAnswerResponse> askQuestion(@Valid @RequestBody AskQuestionRequest request) {
        log.info("收到问答请求，用户ID：{}，问题：{}", request.getUserId(), request.getQuestion());
        
        QuestionAnswerService.QuestionAnswerResult result = 
                questionAnswerService.askQuestion(request.getQuestion(), request.getUserId());
        
        QuestionAnswerResponse response = new QuestionAnswerResponse();
        response.setAnswer(result.getAnswer());
        
        // 转换 SourceInfo
        java.util.List<SourceInfo> sources = new java.util.ArrayList<>();
        if (result.getSourceList() != null) {
            for (QuestionAnswerService.SourceInfo serviceSource : result.getSourceList()) {
                SourceInfo controllerSource = new SourceInfo();
                controllerSource.setDocumentName(serviceSource.getDocumentName());
                controllerSource.setScore(serviceSource.getScore());
                controllerSource.setContent(serviceSource.getContent());
                sources.add(controllerSource);
            }
        }
        response.setSources(sources);
        
        response.setHasKnowledge(result.getHasKnowledge());
        response.setQuestionRecordId(result.getQuestionRecordId());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取问答历史记录
     * 
     * @param page 页码（从1开始）
     * @param size 每页大小
     * @param userId 用户ID（可选）
     * @return 分页的问答记录
     */
    @GetMapping("/history")
    public ResponseEntity<Page<QuestionRecord>> getHistory(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long userId) {
        
        log.info("获取问答历史，页码：{}，每页大小：{}，用户ID：{}", page, size, userId);
        
        Page<QuestionRecord> history = questionAnswerService.getHistory(page, size, userId);
        
        return ResponseEntity.ok(history);
    }

    /**
     * 问题请求DTO
     */
    @Data
    public static class AskQuestionRequest {
        /**
         * 问题内容
         */
        @NotBlank(message = "问题内容不能为空")
        private String question;
        
        /**
         * 用户ID
         */
        @NotNull(message = "用户ID不能为空")
        private Long userId;
    }

    /**
     * 问答响应DTO
     */
    @Data
    public static class QuestionAnswerResponse {
        /**
         * 答案内容
         */
        private String answer;
        
        /**
         * 知识来源列表
         */
        private java.util.List<SourceInfo> sources;
        
        /**
         * 是否有相关知识
         */
        private Boolean hasKnowledge;
        
        /**
         * 问答记录ID
         */
        private Long questionRecordId;
    }
    
    /**
     * 知识来源信息
     */
    @Data
    public static class SourceInfo {
        /**
         * 文档名称
         */
        private String documentName;
        
        /**
         * 相关度分数
         */
        private Double score;
        
        /**
         * 引用内容片段
         */
        private String content;
        
        public SourceInfo() {
        }
        
        public SourceInfo(String documentName, Double score, String content) {
            this.documentName = documentName;
            this.score = score;
            this.content = content;
        }
    }
}
